const app = getApp();

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    nickName: "微信用户",
    hasUserInfo: false,
    logged: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    hasMerchantAccess: null,
    hasRiderAccess: null,
    hasSnackAdminAccess: null,
    phoneNumber: '', // 用户手机号
    // 编辑名字相关
    showEditModal: false,
    editNickName: '', // 编辑中的昵称
    // 客服相关
    showCustomerServiceModal: false,
    showWechatQRModal: false,
    wechatQRCode: '', // 微信二维码
    customerServiceConfig: null, // 客服配置
    // 学校维度信息
    schoolName: '',
    schoolCode: '',
  },

  // 页面加载
  onLoad: function () {},

  // 页面显示时，加载用户角色权限信息
  onShow: function () {
    const openId = wx.getStorageSync('openId');
    console.log("openId", openId)
    if (openId) {
      this.loadUserRole(openId);
    }
  },

  onLogin(e) {
    console.log("登陆按钮被触发");
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      console.log("获取成功，加密数据：", e.detail);
      const { encryptedData, iv, cloudID } = e.detail;
      wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getUserInfoRequest: { encryptedData, iv, cloudID}
        },
        success: (res) => {
          console.log('保存用户手机号成功');
          this.loadUserRole(wx.getStorageSync('openId'));
        },
        fail: (err) => {
          console.error('保存用户手机号失败:', err);
        },
      });
    }
  },

  // 获取用户角色信息
  loadUserRole(openId) {
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getUserInfoRequest: { userId: openId }
      },
      success: (res) => {
        console.log('用户角色信息:', JSON.stringify(res.result.data.roleType));
        const roleType = Array.isArray(res.result.data.roleType)
          ? res.result.data.roleType.map(String)
          : [];
        this.setData({
          hasMerchantAccess: roleType.includes('merchant'),
          hasRiderAccess: roleType.includes('schoolDeliver') || roleType.includes('schoolOwner'),
          hasSnackAdminAccess: roleType.includes('snackAdmin'),
          phoneNumber: res.result.data.phone,
          logged: !!res.result.data.phone,
          nickName: res.result.data.nickName || '微信用户' // 从后端获取昵称
        });
      },
      fail: (err) => {
        console.error('获取角色信息失败:', err);
      },
    });
  },

  // 跳转到地址管理页面
  goAddressManagement: function () {
    wx.navigateTo({
      url: '/pages/addressManagement/index',
    });
  },

  // 跳转到我的投诉页面
  goCamplaint: function () {
    wx.navigateTo({
      url: '/pages/myComplaint/index',
    });
  },

  // 商家操作台
  merchantOperation: function () {
    console.log('商家操作台按钮被点击');
    console.log('hasMerchantAccess:', this.data.hasMerchantAccess);
    wx.navigateTo({
      url: '/pages/merchantManagement/index',
      success: (res) => {
        console.log('页面跳转成功:', res);
      },
      fail: (err) => {
        console.error('页面跳转失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 零食铺管理（管理员管理一个楼栋）
  openSnackAdmin: function () {
    const code = wx.getStorageSync('selectedAddress')?.addressCode || '';
    const param = encodeURIComponent(JSON.stringify({ schoolCode: code}));
    wx.navigateTo({ url: `/pages/snacksAdmin/index?param=${param}` });
  },

  // 读取学校信息（来源于本地选中地址或默认）
  loadSchoolInfo() {
    try {
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const code = selectedAddress?.addressCode || selectedAddress?.schoolCode || 'xue_chang_zhi_ye';
      const name = selectedAddress?.addressName || selectedAddress?.schoolName || '';
      this.setData({ schoolCode: code, schoolName: name });
    } catch (e) {
      console.warn('loadSchoolInfo failed', e);
    }
  },

  // 骑手操作台
  ridertOperation: function () {
    wx.navigateTo({
      url: '/pages/riderOperation/index',
    });
  },
  // 显示客服选择弹窗
  async showCustomerServiceModal() {
    try {
      // 从本地缓存获取选中的地址
      const selectedAddress = wx.getStorageSync('selectedAddress');
      let schoolCode = "xue_chang_zhi_ye"; // 默认值

      // 如果缓存中有选中的地址，使用其addressCode作为schoolCode
      if (selectedAddress && selectedAddress.addressCode) {
        schoolCode = selectedAddress.addressCode;
      }

      // 获取客服配置
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: { 
          getConfigRequest: {
            configName: "customServiceConfig",
            schoolCode: schoolCode
          }
        }
      });
      
      console.log("客服配置获取结果:", JSON.stringify(res));
      
      if (res.result && res.result.data) {
        this.setData({
          customerServiceConfig: res.result.data,
          showCustomerServiceModal: true
        });
      } else {
        wx.showToast({
          title: '获取客服配置失败',
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('获取客服配置出错:', err);
      wx.showToast({
        title: '获取客服配置出错',
        icon: 'none'
      });
    }
  },

  // 隐藏客服选择弹窗
  hideCustomerServiceModal() {
    this.setData({
      showCustomerServiceModal: false
    });
  },

  // 拨打电话客服
  callPhoneService() {
    const config = this.data.customerServiceConfig.content;
    if (!config || !config.phone) {
      wx.showToast({
        title: '电话客服配置不存在',
        icon: 'none'
      });
      return;
    }

    wx.makePhoneCall({
      phoneNumber: config.phone,
      success: () => {
        console.log('拨打电话成功:', config.phone);
        this.hideCustomerServiceModal();
      },
      fail: (err) => {
        console.error('拨打电话失败:', err);
        wx.showToast({
          title: '拨号失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 显示微信客服
  showWechatService() {
    const config = this.data.customerServiceConfig.content;
    if (!config || !config.wechatQRCode) {
      wx.showToast({
        title: '微信客服配置不存在',
        icon: 'none'
      });
      return;
    }

    console.log('微信二维码URL:', config.wechatQRCode);

    // 先测试图片是否可以加载
    wx.getImageInfo({
      src: config.wechatQRCode,
      success: (res) => {
        console.log('图片加载成功:', res);
        this.setData({
          wechatQRCode: config.wechatQRCode,
          showWechatQRModal: true,
          showCustomerServiceModal: false
        });
      },
      fail: (err) => {
        console.error('图片加载失败:', err);
        wx.showToast({
          title: '二维码图片加载失败',
          icon: 'none'
        });
      }
    });
  },

  // 隐藏微信二维码弹窗
  hideWechatQRModal() {
    this.setData({
      showWechatQRModal: false,
      wechatQRCode: ''
    });
  },

  // 二维码图片加载成功
  onQRCodeLoad(e) {
    console.log('二维码图片加载成功:', e);
  },

  // 二维码图片加载失败
  onQRCodeError(e) {
    console.error('二维码图片加载失败:', e);
    wx.showToast({
      title: '二维码图片加载失败',
      icon: 'none'
    });
  },

  // 运营配置
  operationConfig: function () {
    wx.navigateTo({
      url: '/pages/operationConfig/index',
    });
  },

  // 显示编辑Modal
  showEditModal: function() {
    this.setData({
      showEditModal: true,
      editNickName: this.data.nickName
    });
  },

  // 隐藏编辑Modal
  hideEditModal: function() {
    this.setData({
      showEditModal: false,
      editNickName: ''
    });
  },

  // 点击Modal遮罩层
  onModalOverlayTap: function() {
    this.hideEditModal();
  },

  // 点击Modal内容区域（阻止事件冒泡）
  onModalContentTap: function() {
    // 什么都不做，阻止事件冒泡到遮罩层
  },

  // 输入框内容变化
  onNickNameInput: function(e) {
    this.setData({
      editNickName: e.detail.value
    });
  },

  // 保存昵称
  saveNickName: function() {
    const newNickName = this.data.editNickName.trim();
    
    // 验证输入
    if (!newNickName) {
      wx.showToast({
        title: '请输入账号名称',
        icon: 'none'
      });
      return;
    }

    if (newNickName.length > 20) {
      wx.showToast({
        title: '账号名称不能超过20个字符',
        icon: 'none'
      });
      return;
    }

    // 显示加载状态
    wx.showLoading({
      title: '保存中...'
    });

    // 调用后端接口保存昵称
    const openId = wx.getStorageSync('openId');
    if (!openId) {
      wx.hideLoading();
      wx.showToast({
        title: '用户未登录',
        icon: 'none'
      });
      return;
    }

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        updateUserInfoRequest: {
          userId: openId,
          updateFields: {
            nick_name: newNickName
          }
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('保存昵称接口返回:', res);
        
        if (res.result.code === 200) {
          // 更新本地显示
          this.setData({
            nickName: newNickName,
            showEditModal: false,
            editNickName: ''
          });
          
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.result.message || '保存失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('保存昵称失败:', err);
        wx.showToast({
          title: '网络错误，保存失败',
          icon: 'none'
        });
      }
    });
  },
});